
import URL from '@/util/url.js';

//登录
let base_url = URL.BASE_URL;
//二维码
let qrcode_url = URL.QRCODE_URL;
import store from "@/store"
let defaultConfig = {
	isLoading: true
}
const send = (config) => {
	// console.info('Bearer ' + uni.getStorageSync('token'))

	return new Promise((resolve, reject) => {
		Object.assign(config, defaultConfig);

		if(config.isLoading){
			uni.showLoading({
				mask: true
			});
		}
		
		uni.request({
			method: config.method || 'get',
			url: config.is_qrcode === '2' ? qrcode_url + config.url : base_url + config.url,
			data: config.data,
			timeout: 50000,
			header: (() => {
				let base_config = {
					'Content-Type': 'application/json',
				}

				if(config.contentType == 'form'){
					base_config['Content-Type'] = 'application/x-www-form-urlencoded';
				}

				if (config.url.indexOf('/login') != -1) {
					base_config['Authorization'] = 'Basic ' + store.getters.userloginform.name + ':' + store.getters.userloginform.password
				}
				//判断是否有token
				if (uni.getStorageSync('token') && config.isAuth !== false) {
					base_config['Authorization'] = 'Bearer ' + uni.getStorageSync('token')
				}
				return base_config
			})(),
			complete: (result) => {
				if(config.isLoading){
					uni.hideLoading();
				}


				let { data } = result;
				if (data && data.code == 200) {
					return resolve(data)
				} else {
					if (data && data.code == 401) {
						uni.removeStorageSync('token');
						uni.removeStorageSync('userInfo');

						uni.showToast({
							title: data.msg,
							icon: "none"
						})

						uni.navigateTo({
							url: '/pages/login'
						});
					}else if (data && data.code == 410){
						uni.showToast({
							title: data.msg,
							icon: "none"
						})
						uni.removeStorageSync('token');
						uni.removeStorageSync('userInfo');
						uni.navigateTo({
							url: '/pages/login'
						});
					} else {
						uni.showToast({
							title: data.msg,
							icon: "none"
						})
					}

					reject(data);
				}
			}
		})
	})
}

export function request(config) {
	return send(config)
}

export const uploadFile = (config) => {
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: base_url + config.url, //仅为示例，非真实的接口地址
		    filePath: config.tempFilePath,
		    name: 'file',
		    formData: config.data,
			header: (() => {
				let base_config = {};

				if (uni.getStorageSync('token')) {
				    base_config['Authorization'] = `Bearer ${uni.getStorageSync('token')}`;
				}

			    return base_config;
			})(),
		    success: (uploadFileRes) => {
				resolve(uploadFileRes);
		    },
			fail() {
				reject();
			}
		});
	})
}
